<template>
  <div class="star-analysis-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="星级">
          <el-select v-model="filterForm.starLevel" placeholder="请选择星级" clearable>
            <el-option label="五星级" value="5" />
            <el-option label="四星级" value="4" />
            <el-option label="三星级" value="3" />
            <el-option label="二星级" value="2" />
            <el-option label="一星级" value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="分公司">
          <el-select v-model="filterForm.companyId" placeholder="请选择分公司" clearable>
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 星级概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="4" v-for="star in starOverview" :key="star.level">
        <el-card class="star-card" :class="`star-${star.level}`">
          <div class="star-item">
            <div class="star-header">
              <div class="star-icon">
                <el-rate
                  v-model="star.level"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}星"
                />
              </div>
            </div>
            <div class="star-stats">
              <div class="stat-item">
                <div class="stat-value">{{ star.count }}</div>
                <div class="stat-label">客户数量</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ formatNumber(star.amount) }}</div>
                <div class="stat-label">成交金额（万元）</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 星级分布 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>客户星级分布</span>
          </template>
          <div ref="distributionChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 星级成交金额 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>星级成交金额对比</span>
          </template>
          <div ref="amountChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 星级趋势 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>星级客户趋势</span>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>星级客户详细分析</span>
          <div class="header-actions">
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出报表
            </el-button>
            <el-button type="primary" size="small" @click="handleStarUpgrade">
              <el-icon><Star /></el-icon>
              星级升级
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="starLevel" label="星级" width="120" align="center">
          <template #default="{ row }">
            <el-rate
              v-model="row.starLevel"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}星"
            />
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="累计成交金额（万元）" width="160" align="right">
          <template #default="{ row }">
            <span class="amount-text">{{ formatNumber(row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dealCount" label="成交次数" width="100" align="center" />
        <el-table-column prop="avgAmount" label="平均成交金额" width="140" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.avgAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastDealDate" label="最近成交日期" width="120" />
        <el-table-column prop="salesmanName" label="负责业务员" width="120" />
        <el-table-column prop="companyName" label="所属分公司" width="120" />
        <el-table-column prop="customerType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getCustomerTypeTag(row.customerType)">
              {{ getCustomerTypeName(row.customerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="warning" size="small" @click="handleUpgrade(row)">
              升级
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 星级升级对话框 -->
    <el-dialog
      v-model="upgradeDialogVisible"
      title="批量星级升级"
      width="600px"
      @close="handleUpgradeDialogClose"
    >
      <el-form :model="upgradeForm" label-width="100px">
        <el-form-item label="升级条件">
          <el-radio-group v-model="upgradeForm.condition">
            <el-radio label="amount">按成交金额</el-radio>
            <el-radio label="count">按成交次数</el-radio>
            <el-radio label="manual">手动选择</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="upgradeForm.condition === 'amount'" label="最低金额">
          <el-input-number
            v-model="upgradeForm.minAmount"
            :min="0"
            :precision="2"
            placeholder="请输入最低成交金额"
          />
          <span style="margin-left: 10px;">万元</span>
        </el-form-item>
        
        <el-form-item v-if="upgradeForm.condition === 'count'" label="最少次数">
          <el-input-number
            v-model="upgradeForm.minCount"
            :min="1"
            placeholder="请输入最少成交次数"
          />
          <span style="margin-left: 10px;">次</span>
        </el-form-item>
        
        <el-form-item label="目标星级">
          <el-rate
            v-model="upgradeForm.targetStar"
            show-score
            text-color="#ff9900"
            score-template="{value}星"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="upgradeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmUpgrade">确认升级</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Star } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const upgradeDialogVisible = ref(false)
const distributionChartRef = ref<HTMLDivElement>()
const amountChartRef = ref<HTMLDivElement>()
const trendChartRef = ref<HTMLDivElement>()

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  starLevel: '',
  companyId: ''
})

// 升级表单
const upgradeForm = reactive({
  condition: 'amount',
  minAmount: 0,
  minCount: 1,
  targetStar: 5
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 星级概览数据
const starOverview = ref([
  { level: 5, count: 0, amount: 0 },
  { level: 4, count: 0, amount: 0 },
  { level: 3, count: 0, amount: 0 },
  { level: 2, count: 0, amount: 0 },
  { level: 1, count: 0, amount: 0 }
])

// 表格数据
const tableData = ref([])
const selectedRows = ref([])

// 下拉选项
const companyList = ref([])

// 图表实例
let distributionChart: echarts.ECharts | null = null
let amountChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
  updateCharts()
}

const handleReset = () => {
  Object.assign(filterForm, {
    dateRange: [],
    starLevel: '',
    companyId: ''
  })
  handleFilter()
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleStarUpgrade = () => {
  upgradeDialogVisible.value = true
}

const handleUpgrade = (row: any) => {
  ElMessage.info(`升级客户 ${row.customerName} 的星级`)
}

const handleViewDetail = (row: any) => {
  ElMessage.info(`查看客户 ${row.customerName} 的详细信息`)
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const handleUpgradeDialogClose = () => {
  Object.assign(upgradeForm, {
    condition: 'amount',
    minAmount: 0,
    minCount: 1,
    targetStar: 5
  })
}

const handleConfirmUpgrade = () => {
  ElMessageBox.confirm(
    '确定要执行批量星级升级操作吗？',
    '确认升级',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用升级API
    ElMessage.success('星级升级成功')
    upgradeDialogVisible.value = false
    getTableData()
  })
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          customerName: '张三',
          starLevel: 5,
          totalAmount: 850.6,
          dealCount: 12,
          avgAmount: 70.88,
          lastDealDate: '2025-08-15',
          salesmanName: '李四',
          companyName: '北京分公司',
          customerType: 'vip',
          status: 'active'
        },
        {
          customerName: '王五',
          starLevel: 4,
          totalAmount: 420.3,
          dealCount: 8,
          avgAmount: 52.54,
          lastDealDate: '2024-01-10',
          salesmanName: '赵六',
          companyName: '上海分公司',
          customerType: 'enterprise',
          status: 'active'
        }
      ]
      pagination.total = 150
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const initCharts = () => {
  nextTick(() => {
    if (distributionChartRef.value) {
      distributionChart = echarts.init(distributionChartRef.value)
    }
    if (amountChartRef.value) {
      amountChart = echarts.init(amountChartRef.value)
    }
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    updateCharts()
  })
}

const updateCharts = () => {
  updateDistributionChart()
  updateAmountChart()
  updateTrendChart()
}

const updateDistributionChart = () => {
  if (!distributionChart) return
  
  const data = [
    { name: '五星级', value: 45 },
    { name: '四星级', value: 68 },
    { name: '三星级', value: 125 },
    { name: '二星级', value: 89 },
    { name: '一星级', value: 156 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}人 ({d}%)'
    },
    series: [
      {
        name: '客户分布',
        type: 'pie',
        radius: ['40%', '70%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  distributionChart.setOption(option)
}

const updateAmountChart = () => {
  if (!amountChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['一星级', '二星级', '三星级', '四星级', '五星级']
    },
    yAxis: {
      type: 'value',
      name: '成交金额（万元）'
    },
    series: [
      {
        name: '成交金额',
        type: 'bar',
        data: [180.5, 320.8, 680.2, 1250.6, 2150.9],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  amountChart.setOption(option)
}

const updateTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['五星级', '四星级', '三星级', '二星级', '一星级']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '客户数量'
    },
    series: [
      {
        name: '五星级',
        type: 'line',
        data: [40, 42, 43, 44, 45, 45],
        itemStyle: { color: '#ff6b6b' }
      },
      {
        name: '四星级',
        type: 'line',
        data: [60, 62, 65, 66, 67, 68],
        itemStyle: { color: '#4ecdc4' }
      },
      {
        name: '三星级',
        type: 'line',
        data: [110, 115, 118, 120, 122, 125],
        itemStyle: { color: '#45b7d1' }
      },
      {
        name: '二星级',
        type: 'line',
        data: [85, 86, 87, 88, 89, 89],
        itemStyle: { color: '#f9ca24' }
      },
      {
        name: '一星级',
        type: 'line',
        data: [150, 152, 154, 155, 156, 156],
        itemStyle: { color: '#6c5ce7' }
      }
    ]
  }
  trendChart.setOption(option)
}

// 工具方法
const formatNumber = (num: number) => {
  return num?.toFixed(2) || '0.00'
}

const getCustomerTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    personal: 'primary',
    enterprise: 'success',
    vip: 'danger'
  }
  return tagMap[type] || 'info'
}

const getCustomerTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    personal: '个人客户',
    enterprise: '企业客户',
    vip: 'VIP客户'
  }
  return nameMap[type] || type
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    active: 'success',
    inactive: 'danger',
    potential: 'warning'
  }
  return tagMap[status] || 'info'
}

const getStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    active: '活跃',
    inactive: '不活跃',
    potential: '潜在'
  }
  return nameMap[status] || status
}

// 初始化数据
const initData = () => {
  // 初始化概览数据
  starOverview.value = [
    { level: 5, count: 45, amount: 2150.9 },
    { level: 4, count: 68, amount: 1250.6 },
    { level: 3, count: 125, amount: 680.2 },
    { level: 2, count: 89, amount: 320.8 },
    { level: 1, count: 156, amount: 180.5 }
  ]
  
  // 初始化下拉选项
  companyList.value = [
    { id: '1', name: '北京分公司' },
    { id: '2', name: '上海分公司' },
    { id: '3', name: '广州分公司' }
  ]
  
  getTableData()
  initCharts()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.star-analysis-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .overview-row {
    margin-bottom: 20px;
    
    .star-card {
      &.star-5 {
        border-left: 4px solid #ff6b6b;
      }
      
      &.star-4 {
        border-left: 4px solid #4ecdc4;
      }
      
      &.star-3 {
        border-left: 4px solid #45b7d1;
      }
      
      &.star-2 {
        border-left: 4px solid #f9ca24;
      }
      
      &.star-1 {
        border-left: 4px solid #6c5ce7;
      }
      
      .star-item {
        .star-header {
          margin-bottom: 15px;
          
          .star-icon {
            text-align: center;
          }
        }
        
        .star-stats {
          display: flex;
          justify-content: space-between;
          
          .stat-item {
            text-align: center;
            
            .stat-value {
              font-size: 20px;
              font-weight: bold;
              color: #303133;
              margin-bottom: 5px;
            }
            
            .stat-label {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .amount-text {
      color: #67c23a;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
